package priv.dajie.tzzq.bot.buff;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import priv.dajie.tzzq.bot.buff.exception.BuffLoginException;
import priv.dajie.tzzq.bot.exception.NetworkException;
import priv.dajie.tzzq.bot.model.BuffAsset;
import priv.dajie.tzzq.bot.steam.SteamUser;
import priv.dajie.tzzq.bot.steam.exception.SteamLoginException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BuffUser extends SteamUser implements Runnable {

    private boolean login = false;
    private boolean verify = false;
    private Thread keepLoginThread = null;
    private Thread getAssetThread = null;
    private Logger logger = LogManager.getLogger(this.getClass());
    private double alipay = 0;
    private double epay = 0;

    public BuffUser(String userName, String passWord) {
        super(userName, passWord, userName+"buff.cookies");

    }

    BuffUser(String userName, String passWord, String cookiesName) {
        super(userName, passWord, cookiesName);
    }

    @Override
    public void login() throws SteamLoginException, NetworkException, BuffLoginException {
        login(null, null, null);
    }

    public void login(String twofactorcode) throws SteamLoginException {
        login(twofactorcode, null, null);
    }

    @Override
    public void login(String twofactorcode, String emailauth, String code) throws SteamLoginException, NetworkException, BuffLoginException {
        // 判断steam登录情况
        if(!loadCookie("cookies/" +userName+"buff.cookies") || !super.isLogin()){
            super.login(twofactorcode, emailauth, code);
        }
        // 判断buff登录情况, 存在BUG，STEAM的cookies 被 BUFF的cookies覆盖！ （暂时解决方法，删除BUFF的cookies文件），（解决方案，直接读取buff的cookies）
       if (isLogin()){
           return;
       }
        //获取登陆所需的参数
        HttpGet httpGet = new HttpGet("https://buff.163.com/account/login/steam?back_url=/account/steam_bind/finish");
        //打开网页
        String htmlText = open(httpGet, true);
        //分析网页
        Document document = Jsoup.parse(htmlText);
        Element openidForm = document.getElementById("openidForm");
        Elements inputs = openidForm.select("input");
        List<NameValuePair> data = new ArrayList<>();
        //遍历input标签
        for(Element input: inputs){
            if(input.attr("name") != null && !input.attr("name").equals("")){
                data.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }
        }
        //正式登陆
        HttpPost loginPost = new HttpPost("https://steamcommunity.com/openid/login");
        try {
            loginPost.setEntity(new UrlEncodedFormEntity(data));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new BuffLoginException(e.getMessage());
        }
        loginPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        loginPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        loginPost.setHeader("Referer","https://steamcommunity.com/openid/login");
        open(loginPost, true);
        //判断登陆状态，保存cookie
        if(isLogin()) {
            saveCookies();
        }
        else {
            throw new BuffLoginException("登陆失败");
        }
    }

    @Override
    public boolean isLogin() throws NetworkException {
        startKeepThread();
//        startGetAssetThread();

        HttpGet httpGet = new HttpGet("https://buff.163.com/");
        String htmlText = open(httpGet);
//        System.out.println(htmlText);
        Document document = Jsoup.parse(htmlText);
        Elements elements = document.select("div.login-user");
        return !elements.isEmpty();
    }

    private void startKeepThread(){
        synchronized (this) {
            if (keepLoginThread == null) {
                synchronized (this) {
                    keepLoginThread = new Thread(this);
                    keepLoginThread.setDaemon(true); // 设置守护线程
                    keepLoginThread.start();
                }
            }
        }
    }

    private void startGetAssetThread(){
        synchronized (this) {
            if (getAssetThread == null) {
                synchronized (this) {
                    getAssetThread = new Thread(() -> {
                        while (true){
                            try{
                                BuffAsset buffAsset = getAsset();
                            }catch (Exception e){
                                logger.error(e);
                            }finally {
                                try {
                                    Thread.sleep(1000 * 30);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    getAssetThread.setDaemon(true);
                    getAssetThread.start();
                }
            }
        }
    }


    public void sendVerifySms() throws NetworkException {
        HttpPost httpPost = new HttpPost("https://buff.163.com/account/api/logged_in_from_steam/send_authcode");
        httpPost.setHeaders(getBuffHeaders());
        JSONObject json = JSON.parseObject(open(httpPost));
        if (!json.getString("code").equals("OK")) {
            throw new BuffLoginException("获取验证短信失败 :"+json);
        }
    }

    public boolean verify(String code) throws NetworkException {
        HttpPost httpPost = new HttpPost("https://buff.163.com/account/api/logged_in_from_steam/verify_authcode");
        httpPost.setHeaders(getBuffHeaders());
        JSONObject json = new JSONObject();
        json.put("authcode", code);
        StringEntity entity = new StringEntity(json.toString(), "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        String response = open(httpPost);
        System.out.println(response);
        JSONObject verifyJson = JSON.parseObject(response);
        verify = verifyJson.getString("code").equals("OK");
        if(verify) {
            saveCookies();
        }
        return verify;
    }

    public boolean isVerify() throws NetworkException {
        //打开背包api链接 判断code是否为Steam Logged In Needs Verification
        HttpGet httpGet = new HttpGet("https://buff.163.com/api/market/backpack");
        String html = open(httpGet);
        JSONObject json = JSON.parseObject(html);
        String code =  json.getString("code");
        verify = code == null || !code.equals("Steam Logged In Needs Verification");
        return verify;
    }


    public Header[] getBuffHeaders() throws NetworkException { //需要先登陆
        HttpGet httpGet = new HttpGet("https://buff.163.com/");
        String htmlText = open(httpGet);
        Document document = Jsoup.parse(htmlText);
        String csrf = document.select("meta[name=csrf_token]").attr("content");
        String csrfToken = getCookiesByName("csrf_token");
        String session = getCookiesByName("session");
        Header[] headers = {
                new BasicHeader("Referer", "https://buff.163.com/"),
                new BasicHeader("X-CSRFToken", csrf),
                new BasicHeader("Content-Type", "application/json"),
                new BasicHeader("Cookie", "csrf_token="+csrfToken+";session="+session)
        };
        return headers;
    }

    public void logout() throws NetworkException {
        if(login){
            HttpGet httpGet = new HttpGet("https://buff.163.com/account/logout");
            System.out.println(open(httpGet));
            saveCookies();
        }
    }



    @Override
    public void run() {
        while(true){
            boolean islogin = isLogin();
            logger.info("buff防掉线执行状态："+islogin);
            if (!islogin){
                try {
                    login();
                } catch (SteamLoginException e) {
                    e.printStackTrace();
                }
            }

            try {
                Thread.sleep(3600*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public BuffAsset getAsset(){
        String jsonStr = open(new HttpGet("https://buff.163.com/api/asset/get_brief_asset/"));
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject data = jsonObject.getJSONObject("data");
        double alipay = data.getDouble("alipay_amount");
        double epay = data.getDouble("epay_amount");
        this.alipay = alipay;
        this.epay = epay;
        return new BuffAsset(alipay, epay);
    }



    public static void main(String []args) throws NetworkException, SteamLoginException {
        BuffUser buffUser = new BuffUser("13662428660", "g19990214");
        Scanner sc = new Scanner(System.in);
        try {
            buffUser.login();
        }catch (SteamLoginException e) {
            System.out.print("请输入->");
            buffUser.login(sc.nextLine());
        }
        if(!buffUser.isVerify()){
            buffUser.sendVerifySms();
            System.out.print("请输入短信验证码->");
            buffUser.verify(sc.nextLine());
        }
        System.out.println(buffUser.isVerify());

    }

}
